package com.wtwd.campus.receiver;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.constant.SignConstant;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.h5_manager.entity.DeviceLog;
import com.wtwd.campus.h5_manager.service.DeviceLogService;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.service.WarningRecordService;
import com.wtwd.campus.service.WxService;
import com.wtwd.campus.utils.DateUtils;
import com.wtwd.campus.utils.HbDxE15RyUtiils;
import com.wtwd.campus.utils.PushUtils;
import com.wtwd.campus.utils.ReceiverUtils;
import com.wtwd.campus.vcom.common.Constant;
import com.wtwd.campus.vcom.entity.VcomWarningRecord;
import com.wtwd.campus.vcom.service.VcomH5Service;
import com.wtwd.campus.wx.service.WxUtilsService;
import com.wtwd.campus.wx.utils.PushModel;
import com.wtwd.campus.wx.utils.WxUtils;
import org.apache.commons.lang.StringUtils;
import org.jeewx.api.core.req.model.message.TemplateMessageSendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@MsgType(value = Constants.SHUT_DOWN_WARNING)
public class ShtuDownReceiverHandler implements IReceiverHandler {

    @Value("${web.customerCode.xb}")
    private String xbCustomerCode;

    @Value("${web.customerCode.cw}")
    private String cwCustomerCode;

    @Value("${h5.customerId.hbDxRyh5}")
    private Integer hbDxRyh5CustomerId;

    @Value("${wx.general.push.customerCode}")
    private String wxPushCustomerCode;

    @Autowired
    private WxUtilsService wxUtilsService;


    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private WarningRecordService warningRecordService;
    @Autowired
    private PushUtils pushUtils;
    @Autowired
    private ReceiverUtils receiverUtils;
    @Autowired
    private WxService wxService;
    @Autowired
    private VcomH5Service vcomH5Service;
    @Autowired
    private DeviceLogService deviceLogService;
    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqGeneralValueResult mqGeneralValueResult = (MqGeneralValueResult) mqMessage.getObject();
        String imei = mqGeneralValueResult.getImei();
        String commandNumber = mqGeneralValueResult.getCommandNumber();
        //处理指令回复时间
        String date = mqGeneralValueResult.getDeviceDate();
        String time = mqGeneralValueResult.getDeviceTime();
        Long time1 = getTime(date, time);
        DeviceInfo deviceInfo = deviceInfoService.getDeviceByImei(imei);
        if (deviceInfo != null) {
            if(deviceInfo.getDeviceType() == Constants.VCOM_DEVICE){
                //存储威科姆的关机告警
                List<String> studentIds = vcomH5Service.getStudentIdByImei(imei);
                if (studentIds!=null&&studentIds.size()>0){
                    for (String studentId : studentIds) {
                        VcomWarningRecord record=new VcomWarningRecord();
                        record.setType(Constant.WARNING_SHUT_DOWN);
                        record.setTime(time1);
                        record.setImei(imei);
                        record.setStudentId("0");
                        if(!StringUtils.isBlank(studentId)){
                            record.setStudentId(studentId);
                        }
                        vcomH5Service.addVcomWarningRecord(record);
                    }
                }else {
                    VcomWarningRecord record=new VcomWarningRecord();
                    record.setType(Constant.WARNING_SHUT_DOWN);
                    record.setTime(time1);
                    record.setImei(imei);
                    record.setStudentId("0");
                    vcomH5Service.addVcomWarningRecord(record);
                }
            }else {
                //添加告警记录
                WarningRecord record = new WarningRecord();
                record.setDevice_id(deviceInfo.getDeviceId());
                record.setWarning_type(Constants.SHUT_DOWN_WARNING_TYPE);
                record.setWarning_time(time1);
                record.setAddress(deviceInfo.getAddress() == null ? "" : deviceInfo.getAddress());
                warningRecordService.addWarningRecord(record);
            }
            if(deviceInfo.getDeviceType() == Constants.CUSTOMER_DEVICE){
                //关机推送
                pushUtils.pushShutDownWarn(deviceInfo);
            }
            if (deviceInfo.getDeviceType()==Constants.H5_DEVICE){
                if (deviceInfo.getCustomerId()==5||deviceInfo.getCustomerId()==8){
                    pushUtils.hnh5PushAlarmInfo(deviceInfo.getImei(),"关机上报", DateUtils.format(new Date(),DateUtils.dateFormat1),null,null,null);
                }else if (hbDxRyh5CustomerId.equals(deviceInfo.getCustomerId())){
                    HbDxE15RyPushEntity hbDxE15RyPushEntity = new HbDxE15RyPushEntity();
                    hbDxE15RyPushEntity.setImei(deviceInfo.getImei());
                    hbDxE15RyPushEntity.setmType(HbDxE15RyPushEntity.PushTypeEnum.ALARM_TYPE.getType());
                    hbDxE15RyPushEntity.setmClass(HbDxE15RyPushEntity.MessageType.START_DOWN_MESSAGE.getType());
                    hbDxE15RyPushEntity.setmTime(DateUtils.format(new Date(time1), DateUtils.dateFormat4));
                    hbDxE15RyPushEntity.setMemo(MessageFormat.format(HbDxE15RyPushEntity.MessageType.START_DOWN_MESSAGE.getTemplate(),deviceInfo.getImei()));
                    HbDxE15RyUtiils.hbDxE15RyPush(hbDxE15RyPushEntity);
                }
            }
            //如果是平台设备，推送到微信（不推瑞翼和喜马拉雅）
            if(!StringUtils.isBlank(deviceInfo.getOrgCode()) && !deviceInfo.getOrgCode().contains("A01A03A05") && !deviceInfo.getOrgCode().contains("A01A07") && !deviceInfo.getOrgCode().contains("A01A38")){
                //根据学生id查询推送openID
                if(deviceInfo.getStudentId() !=null){
                    List<Map<String, Object>> openIdList = wxService.getOpenIdByStuId(deviceInfo.getStudentId());
                    openIdList.stream().forEach(e->{
                        String stuName=(String)e.get("student_name");
                        String openId=(String)e.get("open_id");
                        if(!StringUtils.isBlank(openId)){
                            String content=stuName.concat("的校园卡已关机");
                            String tip=stuName.concat("的校园卡有一条新的关机记录");
                            if(deviceInfo.getOrgCode().startsWith(cwCustomerCode)){//创维客户的推送
                                TemplateMessageSendResult sosRecordTemplate = PushModel.createWarningTemplateCW(stuName,time1,content,tip);
                                sosRecordTemplate.setUrl("");
                                if(!StringUtils.isBlank(openId)){
                                    sosRecordTemplate.setTouser(openId);
                                    WxUtils.pushMsgCW(sosRecordTemplate);
                                }
                            }else if (deviceInfo.getOrgCode().startsWith(xbCustomerCode)) {
                                TemplateMessageSendResult sosRecordTemplate = PushModel.createWarningTemplateXB(stuName, time1, content, tip);
                                sosRecordTemplate.setUrl("");
                                if(!StringUtils.isBlank(openId)){
                                    sosRecordTemplate.setTouser(openId);
                                    WxUtils.pushMsgXB(sosRecordTemplate);
                                }
                            }else {
                                String pushCode = "";
                                if (StringUtils.isNotBlank(wxPushCustomerCode)&&StringUtils.isNotBlank(deviceInfo.getOrgCode())){
                                    List<String> customerCodeString = Arrays.asList(wxPushCustomerCode.split(SignConstant.COMMA));
                                     pushCode = wxUtilsService.getWxCustomerCode(customerCodeString, deviceInfo.getOrgCode());
                                    if (StringUtils.isNotBlank(pushCode)){
                                        TemplateMessageSendResult warningTemplate = wxUtilsService.createWarningTemplate(pushCode,imei,stuName, time1, content, tip);
                                        warningTemplate.setTouser(openId);
                                        wxUtilsService.pushMsg(pushCode,warningTemplate);
                                    }
                                }
                                if (StringUtils.isBlank(pushCode)){
                                    TemplateMessageSendResult sosRecordTemplate = PushModel.createWarningTemplate(stuName,time1,content,tip);
                                    sosRecordTemplate.setUrl("");
                                    if(!StringUtils.isBlank(openId)){
                                        sosRecordTemplate.setTouser(openId);
                                        WxUtils.pushMsg(sosRecordTemplate);
                                    }
                                }
                            }

                        }
                    });
                }
            }
            //存储设备接收日志
            DeviceLog deviceLog = new DeviceLog();
            deviceLog.setSendUser(Constants.DEVICE_USER);
            deviceLog.setImei(imei);
            deviceLog.setBigType(Constants.SHUT_DOWN_WARNING);
            JSONObject contant = new JSONObject();
            contant.put("设备号", imei);
            contant.put("日期", mqGeneralValueResult.getDeviceDate());
            contant.put("设备状态",mqGeneralValueResult.getDeviceStatus());
            deviceLog.setCmd(contant.toJSONString());
            deviceLog.setSendTime(System.currentTimeMillis());
            deviceLog.setCommandNumber(commandNumber);
            deviceLog.setState(1);
            deviceLogService.addDeviceLog(deviceLog);
        } else {
            saveUnInStorage(imei);
            receiverUtils.cloaseChannel(imei);
        }
    }
}
